<template>
    <div class="table-container">
        <el-table :data="tableData" border style="width: 100%" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
            textAlign: 'center',
            background: '#f5f7fa',
            fontWeight: 'bold',
            position: 'sticky',
            top: 0
        }">
            <el-table-column prop="pro_code" label="产品编号" width="180" />
            <el-table-column prop="stock_name" label="产品名称" />
            <el-table-column prop="pro_brand" label="品牌" />
            <el-table-column prop="stock_model" label="规格型号" />
            <el-table-column prop="dict_code" label="单位">
                <template #default="scope">
                    <span>{{ measureValue(scope.row.dict_code) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="stock_numder" label="当前库存" />
            <el-table-column prop="sale_qty" label="销售数量" />
            <el-table-column prop="pro_sale_price" label="销售单价" />
            <el-table-column prop="pro_total_amount" label="销售金额" />
        </el-table>
        <div style="height: 40px; line-height: 40px;">
            <div style="display: inline-block; float: left;">合计</div>
            <div style="display: inline-block; float:right">销售总数量：{{ sale_total_qty }} &nbsp;&nbsp;&nbsp; 销售总金额：{{
                Number(sale_total_price).toFixed(2) }} &nbsp;&nbsp;&nbsp;产品成本总额：{{
                    Number(cost_total_proce).toFixed(2) }}
            </div>
        </div>
        <div class="pagination-wrapper">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </div>
</template>

<script>
import { ref, reactive, watch, onMounted } from 'vue'
import axios from 'axios'
export default {
    props: {
        detailsData: {
            type: String,
            required: true
        },
        orderCode: String
    },
    setup(props) {
        const tableData = ref()
        const measureOptios = ref([])
        const sale_total_qty = ref(0)//记录销售数量
        const sale_total_price = ref(0)//记录销售金额
        const cost_total_proce = ref(0)//记录成本金额
        const currentPage = ref(1)
        const pageSize = ref(5)
        const pageCount = ref(0)
        onMounted(async() => {
            getMeasure()
            await fillSalesDetails()
            fillSalesDetailsCount()
        })

        //查询计量单位
        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_measure"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                measureOptios.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        //根据计量单位id返回计量单位名称
        function measureValue(row) {
            if (!row) return "无";
            const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        async function fillSalesDetails() {
            sale_total_qty.value = 0;
            sale_total_price.value = 0;
            cost_total_proce.value = 0;
            try {
                const result = await axios.get("http://localhost:5181/api/Sinv_Sale_Order/GetSinv_Sale_Order_Details", {
                    params: {
                        currentPage: currentPage.value,
                        pageSize: pageSize.value,
                        code: props.detailsData,
                        productCode: "",
                        measureId: 0
                    },
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });
                const detailsWithStock = await Promise.all(
                    result.data.map(async (item) => {
                        const stock_numder = await getInv_Stock(item.pro_code);
                        // 计算各项金额
                        const pro_total_amount = Number((item.pro_sale_qty || 0) * (item.pro_sale_price || 0)).toFixed(2);
                        const pro_total_cost = Number((item.pro_sale_qty || 0) * (item.pro_cost_price || 0)).toFixed(2);

                        // 累加总计
                        sale_total_qty.value += Number(item.pro_sale_qty || 0);
                        sale_total_price.value += Number(pro_total_amount);
                        cost_total_proce.value += Number(pro_total_cost);
                        return {
                            stock_name: item.pro_name,
                            stock_model: item.pro_model,
                            dict_code: item.measure_id,
                            sale_qty: item.pro_sale_qty,
                            stock_numder: stock_numder,
                            ...item
                        };
                    })
                );
                tableData.value = detailsWithStock;
                console.info(tableData.value)
                console.info(detailsWithStock)
                //tableData.value = processedData; // 确保赋值解析后的数据
            } catch (err) {
                console.error("请求失败:", err);
            }
        }

        async function getInv_Stock(row) {
            try {
                const result = await axios.get("http://localhost:5181/api/Db_warehouse/GetInv_StockByCode", {
                    params: { code: row },
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });
                return result.data?.stock_numder ?? 0; // 默认值处理
            } catch (err) {
                console.error(err);
                return null;
            }
        }

        //查询销售订单明细总数
        function fillSalesDetailsCount() {
            axios.get("http://localhost:5181/api/Sinv_Sale_Order/GetSinv_Sale_Order_DetailsCount", {
                params: {
                    code: props.detailsData,
                    productCode: "",
                    measureId: 0
                }, headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
            }).then((result) => {
                pageCount.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function handleSizeChange(val) {
            pageSize.value = val;
            fill();
        }

        function handleCurrentChange(val) {
            currentPage.value = val;
            fill();
        }

        return {
            tableData, measureOptios, measureValue, sale_total_price, cost_total_proce, sale_total_qty, currentPage, pageCount, pageSize
            , handleSizeChange, handleCurrentChange
        }
    }
}
</script>

<style scoped>
.pagination-wrapper {
    display: flex;
    justify-content: center;
    /* 水平居中 */
    margin-top: 20px;
    /* 与表格的间距 */
}
</style>